package com.community.service;

import com.community.entity.Member;
import com.feng.fengDUtil.BaseService;
import com.community.util.ExcelReader;
import com.community.util.Search;
import com.feng.fengDUtil.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class MemberService extends BaseService{

    public Page query(Page page, Search search) {
        ArrayList params = new ArrayList();
        String sql = "select * from a_member u  where 1=1 ";
        if(StringUtils.isNotEmpty(search.getPhone())){
            sql+=" and u.content like ? ";
            params.add(processLike(search.getPhone()));
        }
        if(search.getStatus()!=null){
            sql+=" and u.delete_flag = ? ";
            params.add(search.getStatus());
        }
        findPageList(Map.class,sql,page,params.toArray());
        return page;
    }

    public Object uploadMember(MultipartFile file) throws Exception{

        Integer ignored = 0;
        Integer succeeded = 0;
        InputStream ins =  file.getInputStream();
        Workbook wookbook = WorkbookFactory.create(ins);
        Date optime = new Date();
        Sheet sheet = wookbook.getSheetAt(0);
        Integer i_phone_no = 0;
        for(int rowIndex =0,totalRow = sheet.getLastRowNum();rowIndex<=totalRow;rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            if(row==null) continue;
            String phone = ExcelReader.getString(row.getCell(i_phone_no));
            if(StringUtils.isEmpty(phone)){
                continue;
            }
            Long existed = sql("select 1 from a_member where content = ? ").one(Long.class,phone);
            if(existed != null){
                ignored++;
            }else {
                Member member = new Member();
                member.setContent(phone);
                member.setDelete_flag(true);
                member.setCreateTime(optime);
                insert(member);
                succeeded++;
            }
        }
        HashMap data = new HashMap();
        data.put("ignored",ignored);
        data.put("succeeded",succeeded);
        return data;
    }
}
